#!/usr/bin/env python3
import os
import subprocess
import sys


def run_detached(script):
    """启动一个完全独立的子进程，等价于 nohup python script &"""
    log = open(script + ".log", "a")  # 输出重定向
    subprocess.Popen(
        [sys.executable, script],
        stdout=log,
        stderr=subprocess.STDOUT,
        stdin=subprocess.DEVNULL,
        # preexec_fn=os.setsid(),
        creationflags=subprocess.DETACHED_PROCESS,
    )  # 新建会话，脱离终端
    log.close()  # 父进程关掉句柄没关系


if __name__ == "__main__":
    for job in ("run_rspw.py", "run_ionization.py"):
        if not os.path.exists(job):
            sys.exit(f"{job} not found")
        run_detached(job)
    print("Jobs launched in background, you may safely exit.")
